package com.alibaba.service;

import com.alibaba.common.ResponseResult;
import com.alibaba.define.service.UploadService;
import com.alibaba.fastjson.JSON;
import com.alibaba.utils.PathUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Objects;

import static com.alibaba.common.SystemConstants.OSS_EXTERNAL_LINK_PREFIX;
import static com.alibaba.define.enums.AppHttpCodeEnum.NOT_SUPPORT_THIS_IMAGE_TYPE;
import static com.alibaba.define.enums.AppHttpCodeEnum.UN_KNOWN_FILE_TYPE;

/**
 * @author : hanyang
 * @date : 2023-11-05 15:36
 **/

@Service
@Setter
@ConfigurationProperties(prefix = "oss")
@Slf4j
public class UploadServiceImpl implements UploadService {

    private String accessKey;

    private String secretKey;

    private String bucket;

    private String domainName;


    @Override
    public ResponseResult<String> uploadImg(MultipartFile img) {

        // 判断文件类型和大小
        String originalFilename = img.getOriginalFilename();
        if (Objects.isNull(originalFilename)) {
            return ResponseResult.error(UN_KNOWN_FILE_TYPE.getCode(), UN_KNOWN_FILE_TYPE.getMsg());
        }
        if (!originalFilename.endsWith(".png") && !originalFilename.endsWith("jpg")) {
            log.error("UploadServiceImpl ==> uploadImg This type of image is not supported:{}", originalFilename);
            return ResponseResult.error(NOT_SUPPORT_THIS_IMAGE_TYPE.getCode(), NOT_SUPPORT_THIS_IMAGE_TYPE.getMsg());
        }

        // 上传文件到OSS
        String filePath = PathUtils.generateFilePath(originalFilename);
        String url = uploadOss(img, filePath);
        log.info("image upload success! url:{}", url);
        return ResponseResult.ok(url);
    }

    public String uploadOss(MultipartFile imgFile, String filePath) {
        // 构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        // ...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);

        try {
            InputStream inputStream = imgFile.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream, filePath, upToken, null, null);
                // 解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                // 返回外链
                return OSS_EXTERNAL_LINK_PREFIX + "//" + domainName + "/" + putRet.key;
            } catch (QiniuException ex) {
                log.error("UploadServiceImpl#uploadOss() QiniuException:{}", JSON.toJSONString(ex));
                if (ex.response != null) {
                    System.err.println(ex.response);

                    try {
                        String body = ex.response.toString();
                        System.err.println(body);
                    } catch (Exception ignored) {
                    }
                }
            }
        } catch (Exception ex) {
            log.error("UploadServiceImpl#uploadOss() Exception:{}", JSON.toJSONString(ex));
        }
        return null;
    }
}
